package ca.cbc.medialib.service;

import ca.cbc.medialib.Bootstrap;
import ca.cbc.medialib.entity.Release;
import ca.cbc.medialib.exception.ThePlatformObjectNotFoundException;

import com.google.common.base.Function;
import com.theplatform.data.api.DataObjectField;
import com.theplatform.data.api.exception.ObjectNotFoundException;
import com.theplatform.data.api.objects.FieldInfo;
import com.theplatform.media.api.client.MediaClient;
import com.theplatform.media.api.client.ReleaseClient;
import com.theplatform.media.api.fields.ReleaseField;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * =============================================
 * Copyright (c) 2011 Canadian Broadcasting Corporation.
 * All rights reserved.
 * <p/>
 * ca.cbc.medialib.service.ReleaseService.java
 * =============================================
 * <p/>
 * PURPOSE:	Manages communicate with thePlatform for Release
 * <p/>
 * =============================================
 * MODIFICATION		LOG	DATE		REASON / Change Request #
 * Liu Yang			Jun 22, 2011	Initial file creation
 * =============================================
 */
/*
 * This class should only be seen inside this package
 */
class ReleaseService extends EntityService {
    private static String[] fields = new String[]{
            ReleaseField.delivery.toString(),
            ReleaseField.mediaId.toString(),
            ReleaseField.fileId.toString(),
            DataObjectField.customValues.toString(),
            DataObjectField.added.toString(),
            DataObjectField.updated.toString(),
            ReleaseField.url.toString(),
            DataObjectField.id.toString()
    };

    private Function<com.theplatform.media.api.data.objects.Release, Release> convertRelease = new Function<com.theplatform.media.api.data.objects.Release, Release>() {
        @Override
        public Release apply(com.theplatform.media.api.data.objects.Release release) {
            //get custom fields
            Map<String, String> releaseInfoMap = new HashMap<String, String>();
            if (release.getCustomValues() != null)
                for (FieldInfo field : release.getCustomValues().keySet()) {
                    String value = release.getCustomValues().get(field).toString();
                    String fieldName = field.getFieldName();
                    releaseInfoMap.put(fieldName, value);
                }

            String releaseUrl = nullOrString(release.getUrl());
            if (releaseUrl != null)
                releaseUrl += "?metafile=false";

            return new Release.Builder().withId(zeroOrLong(removePrefix(nullOrString(release.getId()))))
                    .withMediaId(zeroOrLong(removePrefix(nullOrString(release.getMediaId()))))
                    .withDelivery(nullOrString(release.getDelivery()))
                    .withAddedDate(release.getAdded())
                    .withUpdatedDate(release.getUpdated())
                    .withReleaseUrl(releaseUrl)
                    .withMediaFileId(zeroOrLong(removePrefix(nullOrString(release.getFileId()))))
                    .withYospaceId(zeroOrLong(releaseInfoMap.get("yospaceID")))
                    .buildNew();
        }
    };

    public Release get(long id) throws ThePlatformObjectNotFoundException {
        try {
            com.theplatform.media.api.data.objects.Release r = Bootstrap.instance.getReleaseClient().get(
                    new URI(String.valueOf(id)),
                    fields
            );
            return convertRelease.apply(r);
        } catch (URISyntaxException e) {
            throw new ThePlatformObjectNotFoundException("Release URI Syntex Error", e);
        } catch (ObjectNotFoundException e) {
            throw new ThePlatformObjectNotFoundException("Release object not found", e);
        }
    }

    public void deleteYospaceId(long releaseId, long mediaId) throws ThePlatformObjectNotFoundException {
        try {
            MediaClient mediaClient = Bootstrap.instance.getMediaClient();
            com.theplatform.media.api.data.objects.Media media = mediaClient.get(
                    new URI(String.valueOf(mediaId)),
                    new String[]{DataObjectField.customValues.toString(), DataObjectField.id.toString()}
            );

            String fieldNamespace = null;
            for (FieldInfo field : media.getCustomValues().keySet()) {
                if (field.getFieldName().equals("genre")) {
                    fieldNamespace = field.getNamespace();
                    break;
                }
            }
            //set available in mobile to false
            FieldInfo field2 = new FieldInfo();
            field2.setFieldName("availableInMobile");
            field2.setNamespace(fieldNamespace);
            media.setCustomValue(field2, false);

            mediaClient.update(media);

            ReleaseClient releaseClient = Bootstrap.instance.getReleaseClient();
            com.theplatform.media.api.data.objects.Release release;
            release = releaseClient.get(
                    new URI(String.valueOf(releaseId)),
                    new String[]{DataObjectField.customValues.toString(), ReleaseField.mediaId.toString(), DataObjectField.id.toString()}
            );

            FieldInfo field = new FieldInfo();
            field.setFieldName("yospaceID");
            field.setNamespace(fieldNamespace);
            release.setCustomValue(field, 0);

            releaseClient.update(release);
        } catch (URISyntaxException e) {
            throw new ThePlatformObjectNotFoundException("Release URI Syntex Error", e);
        } catch (ObjectNotFoundException e) {
            throw new ThePlatformObjectNotFoundException("Release object not found", e);
        }
    }

    public void saveYospaceId(long releaseId, long yospaceId) throws ThePlatformObjectNotFoundException {
        try {
            ReleaseClient releaseClient = Bootstrap.instance.getReleaseClient();
            com.theplatform.media.api.data.objects.Release release;
            release = releaseClient.get(
                    new URI(String.valueOf(releaseId)),
                    new String[]{DataObjectField.customValues.toString(), ReleaseField.mediaId.toString(), DataObjectField.id.toString()}
            );

            com.theplatform.media.api.data.objects.Media media = Bootstrap.instance.getMediaClient().get(
                    release.getMediaId(),
                    new String[]{DataObjectField.customValues.toString()}
            );

            String fieldNamespace = null;
            for (FieldInfo field : media.getCustomValues().keySet()) {
                if (field.getFieldName().equals("genre")) {
                    fieldNamespace = field.getNamespace();
                    break;
                }
            }
            FieldInfo field = new FieldInfo();
            field.setFieldName("yospaceID");
            field.setNamespace(fieldNamespace);
            release.setCustomValue(field, yospaceId);
            releaseClient.update(release);
        } catch (URISyntaxException e) {
            throw new ThePlatformObjectNotFoundException("Release URI Syntex Error", e);
        } catch (ObjectNotFoundException e) {
            throw new ThePlatformObjectNotFoundException("Release object not found", e);
        }
    }

//    public Collection<Release> query(Release sample){
//        try {
//            Collection<Query> queries = new ArrayList<Query>();
//            if(!isNullOrEmpty(sample.getDelivery())){
//                new ByDelivery(sample.getDelivery());
//            }
//            if(!isNullOrEmpty(sample.getMediaId())){
//
//                new ByMediaId(new URI(sample.getMediaId()));
//            }
//            if(!isNullOrEmpty(sample.getTitle())){
//                new ByTitle(sample.getTitle());
//            }
//            if(!isNullOrEmpty(sample.getAdCategory())){
//                new ByCustomValue(new FieldInfo("adCategory",Bootstrap.instance.getNameSpace()),sample.getAdCategory());
//            }
//            if(!isNullOrEmpty(sample.getYospaceId())){
//                new ByCustomValue(new FieldInfo("yospaceId",Bootstrap.instance.getNameSpace()),sample.getYospaceId());
//            }
//
//            Feed<com.theplatform.media.api.data.objects.Release> f = Bootstrap.instance.getReleaseClient().getAll(
//                    fields,
//                    queries.toArray(new Query[0]),
//                    null,
//                    null,
//                    false
//            );
//
//            return Collections2.transform(f.getEntries(), convertRelease);
//
//
//        } catch (URISyntaxException e) {
//            logger.warn("Could not convert the release media id to URI: {}", sample.getMediaId());
//            throw new RuntimeException(e);
//        }
//    }

}
